package com.leyou.user.controller;

import com.leyou.common.exceptions.LyException;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.entity.TbUser;
import com.leyou.user.service.TbUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;


@RestController
public class UserController {

    @Autowired
    private TbUserService tbUserService;

    /**
     * 校验数据是否可用
     * @param data
     * @param type
     * @return  true 数据可用  false 数据不可用
     */
    @GetMapping("/check/{data}/{type}")
    public ResponseEntity<Boolean> checkUserData(@PathVariable("data") String data,
                                                 @PathVariable(value = "type") Integer type) {

        return ResponseEntity.ok(tbUserService.checkUserData(data,type));
    }

    /**
     * 发送验证码
     * @param phone
     * @return
     */
    @PostMapping("/code")
    public ResponseEntity<Void> sendCode(@RequestParam(name = "phone")String phone){
        tbUserService.sendCode(phone);
        return ResponseEntity.noContent().build();
    }

    /**
     * 用户注册
     * @param tbUser
     * @return
     */
    @PostMapping("/register")
    public ResponseEntity<Void> register(@Valid TbUser tbUser, BindingResult result, @RequestParam(name = "code")String code){
        if(result.hasErrors()){
//          说明有错误
            String errors = result.getAllErrors().stream().map(ObjectError::getDefaultMessage).collect(Collectors.joining(","));
            throw new LyException(400,errors);
        }
        tbUserService.register(tbUser,code);
        return ResponseEntity.noContent().build();
    }

    /**
     * 根据用户名和密码查询用户信息
     * @param userName
     * @param passWord
     * @return
     */
    @GetMapping("/query")
    public ResponseEntity<UserDTO> queryUser(@RequestParam(name = "username")String userName,
                                             @RequestParam(name = "password")String passWord){
        return ResponseEntity.ok(tbUserService.queryUser(userName,passWord));
    }
}